package com.szgr.baoyin.myview;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.widget.LinearLayout;

import com.szgr.baoyin.R;

/**
 * Created by yang on 15/9/30.
 */
public class IconIndicator extends LinearLayout implements ViewPager.OnPageChangeListener{
    private ViewPager mViewPager;
    ViewPager.OnPageChangeListener mListener;
    private final static int SCROLL_WHAT = 99;
    MyHandler myHandler;
    /**
     * 滚动间隔时间
     */
    private int spentTime = 3000;
    /**
     * 当前显示的序号
     */
    private int curIndex = 1;
    /**
     * 圆点半径
     */
    private int circleRadiu = 10;
    /**
     * 圆点内边距
     */
    private int circlePadding = 3;
    /**
     * 圆点数目
     */
    private int circleCount = 0;
    /**
     * 滑动方向
     * 1为向右，-1为向左
     */
    private int direction = 1;

    private boolean isRunning = false;

    public IconIndicator(Context context) {
        super(context);
        init();
    }

    public IconIndicator(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public IconIndicator(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }


    private void init(){
        setOrientation(LinearLayout.HORIZONTAL);
        myHandler = new MyHandler();
    }

    public void setViewPager(ViewPager viewPager){
        setViewPager(viewPager, 0);
    }

    /**
     * 设置viewPager和初始位置，必须主动调用
     * @param viewPager
     * @param initPos
     */
    public void setViewPager(ViewPager viewPager,int initPos){
        if (mViewPager == viewPager) {
            return;
        }
        if (mViewPager != null) {
            mViewPager.setOnPageChangeListener(null);
        }
        final PagerAdapter adapter = viewPager.getAdapter();
        if (adapter == null) {
            throw new IllegalStateException("ViewPager does not have adapter instance.");
        }
        mViewPager = viewPager;
        viewPager.setOnPageChangeListener(this);
        notifyDataSetChanged();
        setCurrentItem(initPos + 1);
    }

    /**
     * 初始化布局，逐个添加圆点
     */
    private void notifyDataSetChanged(){
        removeAllViews();
        PagerAdapter mAdapter = mViewPager.getAdapter();
        circleCount = mAdapter.getCount()-2;
        for(int i=0;i<circleCount;i++){
            addCircle(i);
        }
        requestLayout();
    }

    /**
     * 添加圆点
     * @param index
     */
    private void addCircle(int index) {
//        CircleView circleView = new CircleView(getContext(),index,circleRadiu);
//        int circleWidth = 2*(circleRadiu+circlePadding);
//        LayoutParams lp = new LayoutParams(circleWidth, circleWidth,1);
//        circleView.setLayoutParams(lp);
//        addView(circleView);

        IconView iconView = new IconView(getContext(),index,circleRadiu);
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.shouyedian);
        int circleWidth = 2*(bitmap.getWidth()/2 + circlePadding);
        LayoutParams lp = new LayoutParams(circleWidth, circleWidth,1);
        iconView.setLayoutParams(lp);
        addView(iconView);
    }

    /**
     * 是否在滚动
     */
    public boolean isRunning() {
        return isRunning;
    }

    public void setIsRunning(boolean isRunning) {
        this.isRunning = isRunning;
    }

    /**
     * 用于不断向主线程发送信息，使行状态改变
     * 在handleMessage()里面调用sendMessageDelayed()可以实现自动无限滚动
     */
    private class MyHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case SCROLL_WHAT:
                    if(isRunning()) {
                        setCurrentItem(curIndex + direction);
                        myHandler.removeMessages(SCROLL_WHAT);
                        myHandler.sendEmptyMessageDelayed(SCROLL_WHAT, spentTime);
                    }
                    break;
            }
        }
    }

    /**
     * 开始自动滚动，必须主动调用
     */
    public void startAutoScroll(){
        setIsRunning(true);
        myHandler.sendEmptyMessageDelayed(SCROLL_WHAT, spentTime);
    }

    public void stopAutoScroll(){
        setIsRunning(false);
    }

    /**
     * 滑动页，同时改变相应的圆点状态
     * @param item 当前页码
     */
    public void setCurrentItem(int item) {
        if (mViewPager == null) {
            throw new IllegalStateException("ViewPager has not been bound.");
        }
        curIndex  = item;
        mViewPager.setCurrentItem(item);

        if(item==0) item= circleCount-1;
        else if(item==circleCount+1) item = 0;
        else item = item-1;
        for (int i = 0; i < circleCount; i++) {//遍历标题，改变选中的背景
            IconView child = (IconView) getChildAt(i);
            boolean isSelected = (i == item);
            child.setSelected(isSelected);
        }
    }

    public void setOnPageChangeListener(ViewPager.OnPageChangeListener listener){
        mListener = listener;
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        if(mListener!=null) mListener.onPageScrolled(position,positionOffset,positionOffsetPixels);
    }

    @Override
    public void onPageSelected(int position) {
        setCurrentItem(position);
        if(mListener!=null) mListener.onPageSelected(position);
    }

    @Override
    public void onPageScrollStateChanged(int state) {
        if(state==ViewPager.SCROLL_STATE_IDLE){//当滑动停止时，判断是否到达边界
            if(curIndex<=0){
                mViewPager.setCurrentItem(circleCount,false);//瞬间跳动到倒数第二页
                curIndex = circleCount;
            }else if(curIndex>=circleCount+1){
                mViewPager.setCurrentItem(1,false);//瞬间跳动到第二页
                curIndex = 1;
            }
        }
        if(mListener!=null) mListener.onPageScrollStateChanged(state);
    }

    /**
     * 设置滑动间隔时间
     * @param spentTime
     */
    public void setSpentTime(int spentTime) {
        this.spentTime = spentTime>0?spentTime:3000;
    }

    /**
     * 设置圆点半径
     * @param circleRadiu
     */
    public void setCircleRadiu(int circleRadiu) {
        this.circleRadiu = circleRadiu>0?circleRadiu:10;
    }

    /**
     * 设置滑动方向
     * @param direction
     */
    public void setDirection(int direction) {
        this.direction = direction>=0?1:-1;
    }

    public void setCirclePadding(int circlePadding) {
        this.circlePadding = circlePadding>0?circlePadding:3;;
    }
}
